#include <WiFi.h>
#include <PubSubClient.h>

// WiFi 网络配置
const char* ssid = "test";
const char* password = "1223334444";

const char* mqtt_server = "broker.emqx.io"; // EMQX公共服务器
const int mqtt_port = 1883;
const char* mqtt_user = ""; // 如果需要用户名
const char* mqtt_password = ""; // 如果需要密码
const char* client_id = "ESP32_Client";
const char* topic = "emgx/AlAgriculture";

WiFiClient espClient;
PubSubClient client(espClient);

// 按键配置
const int buttonPin = 16;
int buttonState = 0;

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(client_id, mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe(topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  // 配置按键
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // 读取按键状态
  buttonState = digitalRead(buttonPin);
  if (buttonState == LOW) { // 按键按下
    delay(50); // 去抖动
    if (digitalRead(buttonPin) == LOW) {
      client.publish(topic, "I am Yongqiu Liu");
      Serial.println("Message sent: I am Yongqiu Liu");
      while (digitalRead(buttonPin) == LOW); // 等待按键释放
    }
  }
}